package com.enjoyor.soa.traffic.server.tsms.handler;

import com.enjoyor.soa.traffic.core.tsms.domain.MsgInfo;
import com.enjoyor.soa.traffic.core.tsms.domain.RltRouteDevice;
import com.enjoyor.soa.traffic.core.tsms.domain.TaskExecuteRecord;
import com.enjoyor.soa.traffic.core.tsms.enums.EnumDicPublic;
import com.enjoyor.soa.traffic.server.tsms.common.RehearseGlobal;
import com.enjoyor.soa.traffic.server.tsms.dubbo.impl.DubboSchemeActionService;
import com.enjoyor.soa.traffic.util.handler.BasicMsgHandler;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接收数据，数据清理
 */
public class CameraControlHandler extends BasicMsgHandler<MsgInfo> {
    private CameraControlHandler() {
        super(1000, "视频抢占报警-视频控制与推送");
    }

    private static CameraControlHandler single;

    public static CameraControlHandler getInstance() {
        if (single == null) {
            synchronized (CameraControlHandler.class) {
                if (single == null) {
                    single = new CameraControlHandler();
                    //最少5个线程 最多加到5个线程，积压20个累加
                    single.setMultiProcess(5, 20, 20);
                }
            }
        }
        return single;
    }


    @Override
    protected boolean task(int taskTimes) {
        return true;
    }

    @SuppressWarnings("unchecked")
	@Override
    protected boolean process(MsgInfo msg) {
    	String executeTaskId = msg.getExecuteTaskId();
        ArrayList<String> deviceidList = (ArrayList<String>) RehearseGlobal.ActionDataPool.get(executeTaskId).get("deviceidList");
        Map<String, Object> lastGeo = (Map<String, Object>) RehearseGlobal.ActionDataPool.get(executeTaskId).get("lastGeo");
        //提前放行距离
        Integer advanceReleaseDistance = (Integer)RehearseGlobal.ActionDataPool.get(executeTaskId).get("advanceReleaseDistance");
        double mapLength = (double) lastGeo.get("distanceStartPointLength");//上一个点距离起点的距离
        // 推送2摄像头
        List<RltRouteDevice> cameraList = (List<RltRouteDevice>) RehearseGlobal.ActionDataPool.get(executeTaskId).get("cameraList");
        if (cameraList != null) {
            int pushCameraListIndex = 0;
            for (int j = 1; j < cameraList.size(); j++) {
                if (cameraList.get(j).getDeviceLength() - mapLength >= 0) {
                    if (RehearseGlobal.ActionDataPool.get(executeTaskId).get("pushCameraListIndex") != null) {
                        pushCameraListIndex = Integer.parseInt(RehearseGlobal.ActionDataPool.get(executeTaskId).get("pushCameraListIndex").toString());
                    }else{
                        pushCameraListIndex=j-1;
                    }
                    if(pushCameraListIndex+1==j){
                        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                        Map<String, Object> deviceMap = new HashMap<String, Object>();
                        List<RltRouteDevice> devlist = new ArrayList<RltRouteDevice>();
                        deviceidList.clear();
                        for (int i = 1; i >= 0; i--) {
                            if (j - i > -1) {
                                RltRouteDevice rltRouteDevice = new RltRouteDevice();
                                rltRouteDevice.setDeviceId(cameraList.get(j - i).getDeviceId());
                                rltRouteDevice.setDeviceName(cameraList.get(j - i).getDeviceName());
                                rltRouteDevice.setDeviceTypeId(cameraList.get(j - i).getDeviceTypeId());

                                rltRouteDevice.setManageId(cameraList.get(j - i).getManageId());
                                rltRouteDevice.setSetBitBefore(cameraList.get(j - i).getSetBitBefore());
                                rltRouteDevice.setSetBitAfter(cameraList.get(j - i).getSetBitAfter());
                                devlist.add(rltRouteDevice);
                            }
                        }
                        deviceMap.put("type", "video");
                        deviceMap.put("cameradevice", devlist);
                        jsonObject.put(RehearseGlobal.ActionDataPool.get(executeTaskId).get("routeId").toString(), deviceMap);
                        InitializeHandler.getInstance().getServerPushServiceImpl().pushMessage("" + executeTaskId, jsonObject);
                        RehearseGlobal.ActionDataPool.get(executeTaskId).put("pushCameraListIndex", j);
                    }
                    break;
                }
            }
            Map<String, Map<String,Object>> lockVideo = RehearseGlobal.VideoLockPool;
            //锁定范围内的视频
            int videoNextIndex = 0;
            if (RehearseGlobal.ActionDataPool.get(executeTaskId).get("pushCameraListIndex") != null) {
            	videoNextIndex = Integer.parseInt(RehearseGlobal.ActionDataPool.get(executeTaskId).get("pushCameraListIndex").toString());
            }
            for (int k = videoNextIndex; k < cameraList.size(); k++) {
            	RltRouteDevice rltVideo = cameraList.get(k);
            	if(rltVideo.getDeviceLength() - mapLength < advanceReleaseDistance) {
            		String lockId = rltVideo.getDeviceId();
            		if (lockVideo.containsKey(lockId)) {
            			com.alibaba.fastjson.JSONObject jsonObject2 = new com.alibaba.fastjson.JSONObject();
            			String clashExecuteTaskId = (String)lockVideo.get(lockId).get("executeTaskId");
            			Map<String,Object> warnTaskMap = (Map<String,Object>)lockVideo.get(lockId).get("warnTaskMap");
            			if(executeTaskId.equals(clashExecuteTaskId) || warnTaskMap.containsKey(executeTaskId)) {
            				continue;
            			}
            			warnTaskMap.put(executeTaskId, TimeHelper.getLongTime());//报警时间
            			lockVideo.get(lockId).put("warnTaskMap", warnTaskMap);//更新冲突任务信息
            			
                        Map<String, String> deviceclashMap = new HashMap<String, String>();
                        String content = "视频：" + rltVideo.getDeviceName() + "已被任务" + RehearseGlobal.ActionDataPool.get(clashExecuteTaskId).get("taskName") + "锁定。";
                        deviceclashMap.put("type", "warn");
                        deviceclashMap.put("recordTime", TimeHelper.dateToLongString());
                        deviceclashMap.put("clash", content);
                        deviceclashMap.put("content", content);
                        jsonObject2.put(RehearseGlobal.ActionDataPool.get(executeTaskId).get("routeId").toString(), deviceclashMap);
                        InitializeHandler.getInstance().getServerPushServiceImpl().pushMessage("" + executeTaskId, jsonObject2);
                        //记录视频冲突信息
        				TaskExecuteRecord taskExecuteRecord = new TaskExecuteRecord();
        				taskExecuteRecord.setExecuteTaskId(executeTaskId);
        				taskExecuteRecord.setIsWarn("1");
        				taskExecuteRecord.setRecordTypeId(EnumDicPublic.WRAN_VIDEO_CLASH.getKey());
        				taskExecuteRecord.setRecordTypeName(EnumDicPublic.WRAN_VIDEO_CLASH.getValue());
        				taskExecuteRecord.setRecordContent(content);
        				InitializeHandler.getInstance().getTaskExecuteRecordService().insertRecord(taskExecuteRecord, "视频冲突");
                    } else {
                        if (lockDevice(lockId)) {
                        	Map<String,Object> videoMap = new HashMap<String,Object>();
                        	videoMap.put("executeTaskId", executeTaskId);
                        	videoMap.put("lockTime", TimeHelper.getLongTime());
                        	videoMap.put("videoInfo", rltVideo);
                        	videoMap.put("warnTaskMap", new HashMap<String,Object>());
                        	lockVideo.put(lockId, videoMap);//锁住成功、存入缓存
                        }
                    }
                }else {
                	break;//大于规定的锁定距离，跳出循环
                }
            }
            //取消视频锁定
            for (Map.Entry<String, Map<String, Object>> m : lockVideo.entrySet()) {
            	String lockId = m.getKey();
            	String executeTaskIdLock = (String)m.getValue().get("executeTaskId");
            	RltRouteDevice rltVideo = (RltRouteDevice)m.getValue().get("videoInfo");
            	if(mapLength - rltVideo.getDeviceLength() >= advanceReleaseDistance && executeTaskId.equals(executeTaskIdLock)) {
            		if (lockDeviceCancel(lockId)) {
            			//取消锁定，从缓存清除
            			lockVideo.remove(lockId);
            		}
            	}
			}
        }
        return true;
    }

    protected boolean lockDevice(String deviceId) {
        //锁定视频预置位
        return true;
    }
    
    protected boolean lockDeviceCancel(String deviceId) {
        //取消锁定视频预置位
        return true;
    }
}
